package cumeo89.chii.client.entry;

import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;

public abstract class AbstractEditor implements Editor {

	private static PopupPanel popup;
	
	static {
		popup = new PopupPanel(false, false);
		popup.setStyleName("editor-popup");
	}
	
	protected String value;
	private EditorListener editorListener;

	public void addEditorListener(EditorListener lis) {
		if (editorListener != null) {
			throw new UnsupportedOperationException();
		}
		editorListener = lis;
	}

	public void removeEditorListener(EditorListener lis) {
		if (editorListener == lis) {
			editorListener = null;
		}
	}

	public void cancelEditing() {
		popup.hide();
		if (editorListener != null) {
			editorListener.editingCancelled(this);
		}
	}

	public boolean stopEditing() {
		popup.hide();
		if (editorListener != null) {
			editorListener.editingSuccessed(this);
		}
		return true;
	}

	public void startEditing(String value, final int left, final int top,
			int width, int height) {
		this.value = value;
		popup.setWidget(getEditorWidget());
		popup.setPopupPositionAndShow(new PositionCallback() {

			public void setPosition(int offsetWidth, int offsetHeight) {
				popup.setPopupPosition(left, top);
			}

		});
	}

	protected abstract Widget getEditorWidget();

	public String getEditedValue() {
		return value;
	}

}
